<template>
  <div>
    <div style="margin: 10px 0">
      <el-input style="width: 200px" class="mr-5" placeholder="请输入角色名称" v-model="roleName"></el-input>
      <el-input style="width: 200px" class="mr-5" placeholder="请输入权限字符" v-model="roleKey"></el-input>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button class="ml-5" type="warning" @click="reSet">重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="openDialog">
        <i class="el-icon-circle-plus-outline" style="margin-right: 5px"/>新增
      </el-button>
      <el-button type="danger" plain @click="batchDelete">
        <i class="el-icon-remove-outline" style="margin-right: 5px"/>批量删除
      </el-button>
    </div>

    <el-table :data="tableData" border stripe :header-cell-class-name="headerBg"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column prop="roleId" label="角色编号" width="70"></el-table-column>
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column prop="roleKey" label="角色权限"></el-table-column>
      <el-table-column label="角色状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-color="#13ce66" inactive-color="#ccc"
                     @change="changeEnable(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button type="info" plain class="el-icon-menu" @click="selectMenu(scope.row)"> 分配菜单</el-button>
          <el-button type="success" plain class="el-icon-edit" @click="openEdit(scope.row)"> 修改</el-button>
          <el-button type="danger" plain class="el-icon-remove-outline" @click="handleRemove(scope.row.roleId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form label-width="80px" size="small">
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称">
              <el-input v-model="from.roleName" placeholder="请输入角色名称" maxlength="30"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色权限">
              <el-input v-model="from.roleKey" placeholder="请输入权限字符串" maxlength="30"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色顺序">
              <el-input-number v-model="from.roleSort" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="from.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="菜单分配" :visible.sync="menuDialogVis" width="30%">
      <el-tree
          :props="props"
          :data="menuData"
          show-checkbox
          check-strictly
          node-key="menuId"
          ref="tree"
          :default-expanded-keys="expends"
          :default-checked-keys="checks">
         <span class="custom-tree-node" slot-scope="{ node, data }">
            <span><i :class="data.icon"></i> {{ data.menuName }}</span>
         </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
        <el-button @click="menuDialogVis = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Role",
  data() {
    return {
      tableData: [],
      roleIds: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      from: {},
      roleName: "",
      roleKey: "",
      status: "",
      dialogFormVisible: false,
      menuDialogVis: false,
      multipleSelection: [],
      menuData: [],
      props: {
        label: 'name',
      },
      expends: [],
      checks: [],
      roleId: 0,
      menuIds: [],
      headerBg: "headerBg",
      title: ""
    }
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      this.request.get("/sys-role/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          roleName: this.roleName,
          roleKey: this.roleKey,
          status: this.status,
        }
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.records;
          this.total = res.data.total;
        }
      })

      this.request.get("/sys-menu/menuIds").then(res => {
        this.menuIds = res.data;
      })
    },
    openDialog() {
      this.dialogFormVisible = true;
      this.from = {};
      this.title = "添加角色";
    },
    async selectMenu(role) {
      this.roleId = role.roleId;
      // 请求菜单数据
      this.request.get("/sys-menu").then(res => {
        this.menuData = res.data;

        // 把后台返回的菜单数据处理成 id数组
        this.expends = this.menuData.map(v => v.menuId);
      })
      this.request.get("/sys-role/roleMenu/" + this.roleId).then(res => {
        this.checks = res.data;
        // 设置父子节点不相关 check-strictly
        // this.menuIds.forEach(menuId => {
        //   if (!this.checks.includes(menuId)) {
        //     this.$nextTick(() => {
        //       this.$refs.tree.setChecked(menuId, false);
        //     })
        //   }
        // })
        this.menuDialogVis = true;
      })
    },
    saveRoleMenu() {
      let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
      let checkedKeys = this.$refs.tree.getCheckedKeys();
      let menuKeys = halfCheckedKeys.concat(checkedKeys);
      this.request.post("/sys-role/roleMenu/" + this.roleId, menuKeys).then(res => {
        if (res.code === 200) {
          this.$message.success("绑定成功");
          this.menuDialogVis = false;
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    changeEnable(row) {
      this.request.post("/sys-role/update", row).then(res => {
        if (res.code === 200) {
          this.$message.success("操作成功！");
        }
      })
    },
    submitForm() {
      this.request.post("/sys-role", this.from).then(res => {
        this.dialogFormVisible = false;
        if (res.code === 200) {
          this.$message.success("保存成功");
          this.load();
        } else {
          this.$message.error("保存失败");
        }
      })
    },
    openEdit(row) {
      this.from = row;
      this.dialogFormVisible = true;
      this.title = "修改角色";
    },
    handleRemove(id) {
      this.$confirm('是否确认删除角色编号为"' + id + '"的数据项？').then(() => {
        this.request.delete("/sys-role/" + id).then(res => {
          if (res.code === 200) {
            this.$message.success("删除成功");
            this.load();
          } else {
            this.$message.error("删除失败");
          }
        })
      })
    },
    handleSelectionChange(val) {
      console.log(val);
      this.roleIds = val;
    },
    batchDelete() {
      let ids = this.roleIds.map(v => v.roleId);
      this.$confirm('是否确认删除这些角色').then(() => {
        this.request.post("/sys-role/batchDelete", ids).then(res => {
          if (res.code === 200) {
            this.$message.success("批量删除成功");
            this.load();
          } else {
            this.$message.error("删除失败");
          }
        })
      })
    },
    reSet() {
      this.roleName = "";
      this.roleKey = "";
      this.status = "";
      this.load();
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.load();
    }
  }
}
</script>

<style>
.headerBg {
  background-color: #eee !important;
}
</style>
